<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>loki</title>
</head>
<body>
<script src="https://cdn.bootcdn.net/ajax/libs/lokijs/1.5.9/lokijs.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/lokijs/1.5.9/loki-indexed-adapter.min.js"></script>
<script type="module">

    var db = new loki('Example');

    console.log('run', db)

    db.on('trigger', (data) => {
        console.log('trigger', data)
    });


    //     ['changes',
    //     'close',
    //     'flushChanges',
    //     'init',
    //         'sort',
    //         'filter',
    //         'rebuild',
    //         'pre-insert',
    //         'insert',
    //     'loaded',
    //     'warning'].forEach(listenName => {
    //     db.on(listenName, (ev) => {
    //         console.log('!!!!!',listenName, ev)
    //     })
    // })

    db.loadDatabase({}, error => {
        error && console.log(error)
    })
    let coll = db.getCollection('users', {
        unique: ["name"]
    })

    console.log('判断是否存在 collection', coll)


    if (!coll) {
        console.log('无 coll, 需要创建 users')
        // create col
        coll = db.addCollection('users', {indices: ['email']});
        // add data
        var odin = coll.insert({name: 'odin', id: 0, email: 'odin.soap@lokijs.org', age: 38});
        var thor = coll.insert({name: 'thor', id: 1, email: 'thor.soap@lokijs.org', age: 25});
        var stan = coll.insert({name: 'stan', email: 'stan.soap@lokijs.org', age: 29});
        var oliver = coll.insert({name: 'oliver', email: 'oliver.soap@lokijs.org', age: 31});
        var hector = coll.insert({name: 'hector', email: 'hector.soap@lokijs.org', age: 15});
        var achilles = coll.insert({name: 'achilles', email: 'achilles.soap@lokijs.org', age: 31});

        db.saveDatabase(error => {
            console.log('保存数据')
            error && console.log(error)
        })
    }

    coll.on('update', (event) => {
        console.log('coll change 事件', event)
    })

    // 获取数据-直接调用

    const dv = coll.addDynamicView('test');

    dv.applyFind({'name': 'odin'});

    const results = dv.data();

    console.log('获取数据 1', results)
    db.emit('trigger', 'qwerty')

    // ------------

    const dv2 = coll.addDynamicView('test2');

    dv2.applyWhere(function (obj) {
        return obj.name === 'oliver';
    });

    const results2 = dv2.data();

    console.log('获取数据 2', results2)

    // ------------

    const dv3 = coll.addDynamicView('test3');

    dv3.applySimpleSort("age");

    const results3 = dv3.data();

    console.log('获取数据 3', results3)


    // -------------


    const results4 = coll.find({'age': {'$aeq': 15}});

    console.log('获取数据 4', results4)

    // -------------


    const results5 = coll.findOne({'age': {'$aeq': 31}});

    console.log('获取数据 5', results5)

    // -------------


    const results6 = coll.findObject({'age': 38});

    console.log('获取数据 6', results6)

    // -------------


    const results7 = coll.findObjects({'age': 31});

    console.log('获取数据 7', results7)


    // 获取数据-链式调用

    const resultsLine1 = coll.chain().data();

    console.log('获取数据chain 1', resultsLine1)

    // ------------

    const resultsLine2 = coll.chain().find({'name': 'odin'}).data();

    console.log('获取数据chain 2', resultsLine2)

    // ------------

    const resultsLine3 = coll.chain().simplesort('age').data();

    console.log('获取数据chain 3', resultsLine3)

    // 修改:
    const item = coll.findOne({'age': {'$aeq': 31}});

    item.age = 18

    coll.update(item);

    console.log('修改结果 1', coll.chain().data())

    // --------

    coll.findAndUpdate({'age': {'$aeq': 25}}, data => {
        // 原名"thor"
        data.name = 'grewer'
        return data
    })

    console.log('修改结果 2', coll.chain().data())


    // --------

    coll.updateWhere(data => {
        return data.name === 'grewer';
    }, data => {
        // console.log(data)
        data.age = '999'
        return data
    })
    console.log('修改结果 3', coll.chain().data())


    // ------------


    var collection = db.addCollection("test", {
        unique: ["name"],
        // transactional: true
    });

    collection.insert({owner: 0, name: 'Betsy'});
    collection.insert({owner: 1, name: 'Bingo'});
    collection.insert({owner: 2, name: 'Fifi'});
    collection.insert({owner: 3, name: 'Fuzzy'});
    const Gizmo = collection.insert({owner: 4, name: 'Gizmo'});


    try {
        collection.startTransaction()
        Gizmo.name = 'Fuzzy'
        collection.update(Gizmo)
        collection.commit()
    } catch (e) {
        collection.rollback()
        alert(e)
    }

    console.log('修改结果 4', collection.chain().data())

    const resultSet = coll.eqJoin(collection.chain(), 'id', 'owner')
    console.log('连表', resultSet.data())

    // 删除:
    const item2 = coll.findOne({'age': {'$aeq': 31}});

    coll.remove(item2);

    console.log('删除结果 1', coll.chain().data())

    // --------

    coll.findAndRemove({'age': {'$aeq': 15}})

    console.log('删除结果 2', coll.chain().data())

    // --------

    coll.findAndRemove({'age': {'$aeq': 15}})

    console.log('删除结果 2', coll.chain().data())


    // --------

    coll.removeWhere((value, index) => {
        return index === 1
    })

    console.log('删除结果 3', coll.chain().data())


    var tx = [
        {
            type: 'find',
            value: {
                'name': 'oliver'
            }
        }
    ];
    console.log(coll.chain(tx).data())


    db.close()
</script>
</body>
</html>
